import axios from 'axios'
// import {isPcEnable, user, token} from '../config'
const {isPcEnable, token} = require('../config')

export const state = () => ({
  authUser: null,
  accessToken: ''
})

export const mutations = {
  SET_USER: function (state, user) {
    state.authUser = user
  },
  SET_ACCESS_TOKEN: function (state, accessToken) {
    state.accessToken = accessToken
  }
}

export const actions = {
  // nuxtServerInit is called by Nuxt.js before server-rendering every page
  nuxtServerInit({ commit }, { store, req, redirect }) {
    let accessToken = isPcEnable ? token : req.session.accessToken

    commit('SET_ACCESS_TOKEN', accessToken)
    process.accessToken = accessToken
  },
  async login({ commit }, { username, password }) {
    try {
      const { data } = await axios.post('/api/login', { username, password })
      commit('SET_USER', data)
    } catch (error) {
      if (error.response && error.response.status === 401) {
        throw new Error('Bad credentials')
      }
      throw error
    }
  },

  async logout({ commit }) {
    await axios.post('/api/logout')
    commit('SET_USER', null)
  }

}
